import modelExtend from 'dva-model-extend'
import api from 'api'
import { pathMatchRegexp } from 'utils'
import { pageModel } from 'utils/model'
import { message } from 'antd'

const { queryalluser, setauths } = api

export default modelExtend(pageModel, {
  namespace: 'userauths',

  state: {
    // data: {},
    // select: '',
  },

  subscriptions: {
    setup({ dispatch, history }) {
      history.listen(location => {
        let match = pathMatchRegexp('*/auths/userauth', location.pathname)
        if (match) {
          let payload =
            location.query.page != undefined &&
            location.query.pageSize != undefined
              ? location.query
              : { page: 1, pageSize: 10 }
          payload = {
            ...payload,
            name: location.query.name ? location.query.name : '',
          }
          dispatch({
            type: 'query',
            payload: {
              ...location.query,
              ...payload,
            },
          })
        }
      })
    },
  },

  effects: {
    *query({ payload }, { call, put, select }) {
      const { result } = yield call(queryalluser, payload)
      yield put({
        type: 'querySuccess',
        payload: {
          list: result.data,
          pagination: {
            current: Number(payload.page) || 1,
            pageSize: Number(payload.pageSize) || 10,
            total: result.total,
          },
        },
      })
    },
    *setauths({ payload }, { call }) {
      message.loading('修改中...', 0)
      yield call(setauths, payload)
      message.destroy()
      message.success('修改成功')
    },
  },

  reducers: {
    setAuths(state, { payload }) {
      state.data = payload
    },
  },
})
